<?php
/**
 * Created by PhpStorm.
 * User: cuishenghu
 * Date: 2018/12/6
 * Time: 14:35
 */

namespace app\admin\controller;

use app\common\model\BaseModel;
use think\Controller;

class Category extends Base
{
    //分类列表
    public function index()
    {
        $category = new BaseModel('category');
        $selectResult = $category->getPageList(['status'=>0]);
        // 拼装参数
        foreach($selectResult as $key=>$vo){
            $selectResult[$key]['operate'] = $this->makeButton($vo);
        }
        $this->assign('list', $selectResult);

        return $this->fetch();
    }

    // 设置分类
    public function edit()
    {
        $id = input('param.id');
        $category = new BaseModel('category');
        if(!empty($id)){
            $current = $category->getOne(['id'=>$id]);
            $this->assign([
                'category' => $current
            ]);
        }
        if(request()->isAjax()){
            $param = input('post.');
            if(strlen($param['name']) < 18){
                return json(['code'=>-2, 'msg'=>'身份证号格式不对！']);
            }
            $param['update_time'] = date('Y-m-d H:i:s');
            if(empty($id)){
                $param['create_time'] = $param['update_time'];
            }
            $flag = $category->modify($param);

            return json(msg($flag['code'], $param['id']?:0, $flag['msg']));
        }
        return $this->fetch();
    }

    // 删除分类
    public function delete()
    {
        $id = input('param.id');

        $category = new BaseModel('category');
        $flag = $category->remove($id);

        return json(msg($flag['code'], 0, $flag['msg']));
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        return showOperate([
            '置顶' => [
                'auth' => 'notice/top',
                'href' => "javascript:topping(" .$id .")",
                'btnStyle' => 'success'
            ],
            '维护信息' => [
                'auth' => 'notice/edit',
                'href' => url('notice/edit', ['id' => $id]),
                'btnStyle' => 'primary'
            ],
            '删除' => [
                'auth' => 'notice/delete',
                'href' => "javascript:deleteNotice(" .$id .")",
                'btnStyle' => 'danger'
            ]
        ]);
    }
}